<?php 
class Register extends BZ_Controller
{
    public function _init()
    {
        $this->load->helper(array('email'));
        $this->load->model('user_model', 'user');
        $this->load->model('user_account_model', 'user_account');
    }
    
    /**
     * 注册页面
     */
    public function index()
    {
        if ($this->frontUser) {
            $this->redirect($this->config->wap_base_url);
        }
        $username = $this->input->get('username');
        if (!empty($username)) {
            $this->data['parent_id'] = $username;
        } else {
            $this->data['parent_id'] = get_cookie('user_name');
        }
        $this->data['captcha'] = $this->getCaptcha();
        $this->load->view('register/index', $this->data);
    }
    
    /**
     * 注册提交页面
     */
    public function doRegister()
    {
        $username    = $this->input->post('username');
        $mobilePhone = $this->input->post('mobile_phone');
        $code        = $this->input->post('verify');
        $endTime     = date('Y-m-d H:i:s');
        if (!valid_mobile($mobilePhone)) {
            $this->ajaxJson(false, '手机号码格式有误');
        }
        if ($this->input->post('password') != $this->input->post('confirm_password')) {
            $this->ajaxJson(false, '密码输入不一致');
        }
        if (!$this->input->post('is_check')) {
            $this->ajaxJson(false, '用户协议必选');
        }
        $verify = $this->user_code->findOne(['mobile' => $mobilePhone, 'code' => $code], 'id, end_time');//, 'end_time' => $endTime
        if ($verify->num_rows() <= 0) {
            $this->ajaxJson(false, '手机验证码错误');
        }
        if ($verify->row(0)->end_time < $endTime) {
            $this->ajaxJson(false, '手机验证码超过有效期，请重新获取~');
        }

        $result = $this->user->validateName($this->input->post('username'));
        if ($result->num_rows() > 0) {
            $this->ajaxJson(false, '该用户名已经存在');
        }
        $result = $this->user->validateMobilePhone($this->input->post('mobile_phone'));
        if ($result->num_rows() > 0) {
            $this->ajaxJson(false, '该手机号码已经注册');
        }
        if ($this->input->post('parent_id')) {
            $parent = $this->user->validateName($this->input->post('parent_id'));
            if ($parent->num_rows() > 0) {
                $parent_id = $parent->row()->uid;
            } else {
                $this->ajaxJson(false, '推荐人不存在');
            }
        } else {
            $parent_id = UTID_BEIZHU;
        }
        
        $this->db->trans_start();
        $userId = $this->user->insertUser($this->input->post(), $parent_id);
        $insertAccount = [
            'uid'          => $userId,
            'amount_carry' => 0,
            'poundage'     => 0,
            'amount_bonus' => ($parent_id != UTID_BEIZHU) ? 300 : 0
        ];
        $userAccountId = $this->user_account->insert($insertAccount);
        $this->db->trans_complete();
        if (!$userId && !$userAccountId && $this->db->trans_status() === FALSE) {
            $this->ajaxJson(false, '服务器忙，请稍候再试');
        }
        
        $userType = $this->usertype(UTID_CUSTOMER);
        $session = array(
            'ACT_UID'        => $userId,
            'ACT_UTID'       => UTID_CUSTOMER,
            'ACT_TYPENAME'   => urlencode($userType['type_zh']),
            'ACT_TYPE'       => $userType['type_en'],
            'ACT_EXTRA'      => 0,
            'ALIAS_NAME'     => urlencode($username),
            'OWNER_ID'       => $userId,
            'OWNER_NAME'     => $username,
            'PARENT_ID'      => $parent_id,
            'PERSONAL_PHOTO' => urlencode($user->personal_photo),
        );
        set_cookie('frontUser', serialize($session), 3 * 24 * 3600);
        $this->cache->memcached->save('frontUser', serialize($session), 3 * 24 * 3600);
        $backurl = $this->input->post('backurl') ? urldecode($this->input->post('backurl')) : site_url('register/regsuccess');
        $this->ajaxJson(['status' => true, 'msg' => $backurl]);
    }
    
    /**
     * 注册成功页面
     */
    public function regsuccess()
    {
        $frontUser = $this->frontUser;
        $this->data['username'] = $frontUser['OWNER_NAME'];
        $this->load->view('register/regsuccess', $this->data);
    }
    
    /**
     * 验证用户是否注册过。
     */
    public function validateName()
    {
        $result = $this->user->validateName($this->input->post('username'));
        if ($result->num_rows() > 0) {
            echo 'false';
        } else {
            echo 'true';
        }
        exit;
    }
    
    /**
     * 验证用户是否注册过。
     */
    public function validateMobilePhone()
    {
        $result = $this->user->validateMobilePhone($this->input->post('mobile_phone'));
        if ($result->num_rows() > 0) {
            echo 'false';
        } else {
            echo 'true';
        }
        exit;
    }
    
    /**
     * 验证推荐人是否存在。
     */
    public function validateParentId()
    {
        $result = $this->user->validateName($this->input->post('parent_id'));
        if ($result->num_rows() > 0) {
            echo 'true';
        } else {
            echo 'false';
        }
        exit;
    }
    
    /**
     * 验证验证码是否一致
     */
    public function validateVerify()
    {
        $mobile = $this->input->post('mobile_phone');
        $code   = $this->input->post('verify');
        $time   = date('Y-m-d H:i:s');
        $verify = $this->user_code->findOne(['mobile' => $mobile, 'code' => $code, 'send_time <' => $time, 'end_time >=' => $time], 'id, end_time');//, 'end_time' => $endTime
        if ($verify->num_rows() > 0) { //验证码有效
            echo 'true';
        } else {
            echo 'false';
        }
        exit;
    }
    
    public function checkPhone()
    {
        $phone = $this->input->post('phone');
        $captcha = $this->input->post('captcha');

        if (strtoupper($captcha) != strtoupper(get_cookie('captcha'))) {
            $this->ajaxJson(false, '验证码不正确');
        }
        if (!valid_mobile($phone)) {
            $this->ajaxJson(false, '手机号码格式有误');
        }
        $result = $this->user->validateMobilePhone($phone);
        if ($result->num_rows() > 0) {
            $this->ajaxJson(false, '手机号已注册');
        }

        return $this->sendCommonSms($phone, 'SMS_135430022');
    }
}